package mini.statement;

import java.util.List;
import java.util.LinkedList;

import mini.Env;
import mini.expr.Element;
import mini.expr.Expr;


public class AssignStatement extends Statement {

    private String name;
    private Expr expr;

    public AssignStatement(String id, Expr e) {
        name = id;
        expr = e;
    }

    public void eval(List<Env> listOfEnvs, LinkedList var) {
    	
        /* add name to the statementlist of variable names */
        if (!var.contains(name)) {
            var.add(name);
        }
        
        // Evaluate it...
    	Element elem = expr.eval(listOfEnvs, var);

        if( listOfEnvs != null && listOfEnvs.size() > 0 ) {
        	
        	// Walk backwards through your environments, looking to see if it's something to overwrite
        	boolean alreadySet = false;
        	for( int i = listOfEnvs.size()-1; i >= 0 && !alreadySet; i-- ) {
        		Env env = listOfEnvs.get(i);
        		alreadySet = env.updateInNametable( name, elem );
        	}
        	
        	// If we didn't set it at all, oh well, set it in topmost environmet
        	if( !alreadySet ) {
            	Env env = listOfEnvs.get(listOfEnvs.size()-1);
            	env.addToNametable( name, elem);
        	}
        } else {
        	System.err.println( "Internal error in Assignment Statement of " + name + "=" + expr );
        }
    }

	public String getName() {
		return name;
	}

	public Expr getExpr() {
		return expr;
	}
}